<?php

namespace App\Http\Controllers\Internal;

use App\Models\Course;
use App\Models\Lesson;
use App\Models\LessonSection;

class LessonController extends Controller
{
    /*
     * @api post /courses/{courseId}/lessons 获取课时列表
     * @version 0.0.1
     * @group internal
     *
     * @param path int courseId 课程ID
     *
     * @response 200 正常结果 {
     *  "code":0,
     *  "msg":"",
     *  "data":{
     *  }
     * }
     *
     */
    public function index($courseId)
    {
        if (! $courseId) {
            return $this->sendSuccessJson([]);
        }

        $lessonsObj = Lesson::ofCoursePublishedLesson($courseId)
            ->orderBy('sequence', 'asc')->get();

        $items = [];
        /** @var Lesson $l */
        foreach($lessonsObj as $l) {
            $items[$l->getId()] = [
                'id' => $l->getId(),
                'courseId' => $l->getCourseId(),
                'wordCount' => $l->getWordCount(),
                'knowledgeCount' => $l->getKnowledgeCount(),
                'essenceQaCount' => $l->getEssenceQaCount(),
                'gameTestCount' => $l->getGameTestCount(),
                'gameWordCount' => $l->getGameWordCount(),
                'sequence' => $l->getSequence(),
                'name' => $l->getName(),
            ];
        }
        return $this->sendSuccessJson($items);
    }

    /*
     * @api post /internal/lessons 获取课时列表
     * @version 0.0.1
     * @group internal
     *
     * @param body int lessonIds 课时ID
     *
     * @response 200 正常结果 {
     *  "code":0,
     *  "msg":"",
     *  "data":{
     *    "total":30,
     *    "items":[
     *      "id":"0",
     *      "star":"",
     *      "title":"",
     *      "cover":"",
     *      "date":"",
     *      "day":""
     *    ]
     *  }
     * }
     *
     */
    public function getByLessonIds()
    {
        $this->validate($this->request, [
            'lessonIds' => 'required|array'
        ]);
        $lessonIds = $this->request->input('lessonIds');
        $lessonsObj = Lesson::whereIn('id', $lessonIds)->get();
        $items = [];
        /** @var Lesson $lessonObj */
        foreach ($lessonsObj as $lessonObj) {
            $thumbCover = $lessonObj->thumbCover()->value('uri');
            $cover = $lessonObj->cover()->value('uri');

            if ($thumbCover) {
                $thumbCover .= '?x-oss-process=style/lesson_thumb_cover';
            }
            if ($cover) {
                $cover .= '?x-oss-process=style/lesson_cover';
            }

            $items[$lessonObj->getId()] = [
                'id' => $lessonObj->getId(),
                'name' => $lessonObj->getName(),
                'cover' => $thumbCover,
                'bigCover' => $cover,
                'studiedCount' => $lessonObj->getStudiedCount(),
                'wordCount' => $lessonObj->getWordCount()
            ];
        }
        return $this->sendSuccessJson($items);
    }

    /*
     * @api get /internal/lessons/{lessonId} 获取课时详情
     * @version 0.0.1
     * @group internal
     *
     * @param path int lessonId 课时ID
     *
     * @response 200 正常结果 {
     *  "code":0,
     *  "msg":"",
     *  "data":{}
     * }
     *
     */
    public function show($lessonId)
    {
        $data = [];
        /** @var Lesson $lessonObj */
        $lessonObj = Lesson::find($lessonId);
        if ($lessonObj) {
            $cover = $lessonObj->cover()->value('uri');
            if ($cover) {
                $cover .= '?x-oss-process=style/lesson_cover';
            }
            $data = [
                'id' => $lessonObj->id,
                'name' => $lessonObj->getName(),
                'cover' => $cover,
                'lexile' => $lessonObj->getLexile(),
                'wordCount' => $lessonObj->getWordCount(),
                'knowledgeCount' => $lessonObj->getKnowledgeCount(),
                'audio' => $lessonObj->audio()->value('uri')
            ];
        }
        return $this->sendSuccessJson($data);
    }

    /*
     * @api post /internal/lessons/{lessonId}/studied-count 增加课时学习人数
     * @version 0.0.1
     * @group internal
     *
     * @param path int lessonId 课时ID
     *
     * @response 200 正常结果 {
     *  "code":0,
     *  "msg":"",
     *  "data":{}
     * }
     */
    public function incrStudiedCount($lessonId)
    {
        $data = [];
        /** @var Lesson $lessonObj */
        $lessonObj = Lesson::find($lessonId);
        if ($lessonObj) {
            $lessonObj->increment('studied_count');
        }
        return $this->sendSuccessJson($data);
    }



    /*
     * @api get /internal/lessons/{lessonId}/sections/{section} 获取课时章节
     * @version 0.0.1
     * @group internal
     *
     * @param path int lessonId 课时ID
     * @param path string section 类型ID
     *
     * @response 200 正常结果 {
     *  "code":0,
     *  "msg":"",
     *  "data":{}
     * }
     *
     */
    public function getSection($lessonId, $section)
    {
        $metadata = LessonSection::where(['lesson_id'=>$lessonId, 'section'=>$section])->value('metadata');
        return $this->sendSuccessJson(json_decode($metadata, true));
    }

    /*
     * @api get /internal/lessons/{lessonId}/sources 获取课时所有章节
     * @version 0.0.1
     * @group internal
     *
     * @param path int lessonId 课时ID
     *
     * @response 200 正常结果 {
     *  "code":0,
     *  "msg":"",
     *  "data":{}
     * }
     */
    public function getAllSources($lessonId)
    {
        $sections = LessonSection::where('lesson_id', $lessonId)->get(['section', 'metadata', 'sources']);
        $sources = [];
        foreach ($sections as $item) {
            $item['sources'] && $sources = array_merge_recursive($sources, json_decode($item['sources'], true));
        }
        $sources['images'] = !empty($sources['images']) ? array_values(array_unique($sources['images'])) : [];
        $sources['audios'] = !empty($sources['audios']) ? array_values(array_unique($sources['audios'])) : [];
        $sources['videos'] = !empty($sources['videos']) ? array_values(array_unique($sources['videos'])) : [];
        return $this->sendSuccessJson($sources);
    }

    /*
     * @api get /internal/courses/first-lesson 课程的首节课
     * @version 0.0.1
     * @group internal
     *
     * @param path int lessonId 课时ID
     *
     * @response 200 正常结果 {
     *  "code":0,
     *  "msg":"",
     *  "data":{}
     * }
     */
    public function firstLesson()
    {
        $this->validate($this->request, [
            'level' => 'required|integer'
        ]);
        $level = $this->request->input('level');
        $isOfficial = $this->request->input('isOfficial', 0);

        /** @var Course $courseObj */
        $courseObj = Course::where('level', $level)->first();
        if (!$courseObj) {
            return $this->sendSuccessJson([]);
        }

        /** @var Lesson $lessonObj */
        $sequence = $isOfficial ? 1 : 0;
        $lessonObj = Lesson::where('course_id', $courseObj->getId())->where('sequence', $sequence)->where('is_published', '!=', Lesson::IS_FALSE)->first();
        if (!$lessonObj) {
            return $this->sendSuccessJson([]);
        }

        $result = [
            'courseId' => $courseObj->getId(),
            'firstLessonId' => $lessonObj->getId(),
            'wordCount' => $lessonObj->getWordCount(),
            'knowledgeCount' => $lessonObj->getKnowledgeCount(),
            'essenceQaCount' => $lessonObj->getEssenceQaCount(),
            'gameTestCount' => $lessonObj->getGameTestCount(),
            'gameWordCount' => $lessonObj->getGameWordCount(),
            'sequence' => $lessonObj->getSequence(),
            'name' => $lessonObj->getName(),
            'cover' => $courseObj->cover()->value('uri')
        ];
        return $this->sendSuccessJson($result);
    }

    /*
     * @api get /internal/courses/{courseId}/lesson-total 课程的现有课时数
     * @version 0.0.1
     * @group internal
     *
     * @param path int courseId 课程ID
     *
     * @response 200 正常结果 {
     *  "code":0,
     *  "msg":"",
     *  "data":{}
     * }
     */
    public function lessonTotal($courseId)
    {
        $count = Lesson::where('course_id', $courseId)->count();
        return $this->sendSuccessJson($count);
    }
}
